import {Component, ElementRef, OnInit} from '@angular/core';
import {AdOssUploadService} from "../../../lib/service/ad-oss-upload.service";
import {NzMessageService} from "ng-zorro-antd";
import {ActivatedRoute, Router} from "@angular/router";
import {AliyunOssOutputUrl} from "../../../../config/api";
import {BannerService} from "../banner.service";
import {CategoryService} from '../../category/category.service';


@Component({
  selector: 'app-add',
  templateUrl: './add.component.html',
  styleUrls: ['./add.component.scss'],
  providers: [BannerService, CategoryService]
})

export class AddComponent implements OnInit {
  addActivity = new AddActivity();
  editActivity = new EditActivity();
  fileList = [];
  picList = [];
  task_ids = [];
  checkedTaskInfo = [];
  taskModalVisible = false;
  taskPage = 1;
  taskPageSize = 5;
  taskList = [];
  taskTotal = 0;
  submitStatus = false;
  isShow = false;
  type: string;
  message: string;
  editId = null;
  isChange = false;
  canChange = false;
  categoryList = [];
  page = null;

  merchant_id = '';
  activity_type = '';
  first_category = '';
  second_category = '';
  task_name = '';
  selectedGroup = null;
  typeList = [];
  isConfirmTaskLoading = false;
  picSizeInfo = '图片尺寸建议上传 701px * 351px';


  constructor(
    private adOssUploadService: AdOssUploadService,
    private _message: NzMessageService,
    private bannerService: BannerService,
    private categoryService: CategoryService,
    private router: Router,
    private route: ActivatedRoute,
    private el: ElementRef
  ) {
  }

  ngOnInit() {
    let params = this.route.snapshot.queryParams;
    let id = params['id'];
    params['page'] ? this.page = params['page'] : this.page = null;
    if (id) {
      this.getActivityInfo(id);
      this.editId = id;
    }
    this.getCategoryList();
  }


  picError = false;
  nameError = false;
  commentError = false;
  nameRequired = false;
  commentRequired = false;
  sortRequired = false;
  taskRequired = false;


  fileChange() {
    if (this.canChange) {
      this.isChange = true;
    }
    if (this.fileList.length == 0 && this.picList.length == 0) {
      this.picError = true;
    } else {
      this.picError = false;
    }
  }

  WidthCheck(type, str, maxLen, e?) {
    var w = 0;
    var tempCount = 0;
    if (type == 'name') {
      if (e.length == 0) {
        this.nameRequired = true;
      } else {
        this.nameRequired = false;
      }
    } else {
      if (e.length == 0) {
        this.commentRequired = true;
      } else {
        this.commentRequired = false;
      }
    }

    for (var i = 0; i < str.length; i++) {
      var c = str.charCodeAt(i);
      if ((c >= 0x0001 && c <= 0x007e) || (0xff60 <= c && c <= 0xff9f)) {
        w++;
      } else {
        w += 2;
      }

      if (w > maxLen) {
        // str = str.substr(0, i);
        if (type == 'name') {
          // this.el.nativeElement.querySelector('#activity_name').value = str;
          this.nameError = true;
        } else {
          // this.el.nativeElement.querySelector('#comment').value = str;
          this.commentError = true;
        }
      } else {
        if (type == 'name') {
          this.nameError = false;
        } else {
          this.commentError = false;
        }
      }
    }
  }

  search() {
    this.taskPage = 1;
    this.getTaskList();
  }

  reset() {
    this.merchant_id = '';
    this.activity_type = '';
    this.first_category = '';
    this.second_category = '';
    this.task_name = '';
    this.taskPage = 1;
    this.getTaskList();
  }

  getActivityInfo(id) {
    this.bannerService.getActivityInfo(id).subscribe(res => {
      if (res.code == 200) {
        let data = res.data;
        this.addActivity.activity_name = data.activity_name;
        this.addActivity.type = data.type;
        this.addActivity.sort = data.sort;
        this.addActivity.comment = data.comment;
        this.addActivity.first_category_id = data.first_category_id;
        this.addActivity.pic = data.pic;
        let task_ids = JSON.parse(data.task_ids);
        this.checkedTaskInfo = [];
        this.bannerService.getTaskList(1, 666).subscribe(res => {
          if (res.code == 200) {
            let taskList = res.data.list.data;
            taskList.map((e, i) => {
              e['taskPreview'] = `${AliyunOssOutputUrl}/${e['task_content']['image']}?update=${new Date().getTime()}`;
              task_ids.map((e1, i1) => {
                if (e.id == e1) {
                  this.task_ids.push(e);
                }
              })
            });
            this.checkedTaskInfo = this.task_ids;
          }
        });
        if (data.pic) {
          this.picList.push({src: `${AliyunOssOutputUrl}/${data.pic}?update=${new Date().getTime()}`});
          this.fileList.push('pic');
          this.canChange = true;
        }
      }
    })
  }

  getTaskList() {
    this.bannerService.getTaskList(this.taskPage, this.taskPageSize).subscribe(res => {
      if (res.code === 200) {
        let data = res.data;
        this.taskList = data.list.data;
        this.taskTotal = data.list.total;
        let task_type = data.task_type;
        for (let key in  task_type) {
          this.typeList.push({
            'label': task_type[key],
            'value': key
          })
        }
        ;
        this.taskList.map((e, i) => {
          e['taskPreview'] = `${AliyunOssOutputUrl}/${e['task_content']['image']}?update=${new Date().getTime()}`;
          e['checked'] = false;
          if (this.checkedTaskInfo.length > 0) {
            this.checkedTaskInfo.map((e1, i1) => {
              if (e.id == e1.id) {
                e['checked'] = true;
              }
            })
          }
        });
      }
    })
  }

  getCategoryList() {
    this.categoryService.getCategoryList(1, 0).subscribe(res => {
      if (res.code === 200) {
        this.categoryList = [{'category_name': '全部', 'id': 0}].concat(res.data);
        this.addActivity.first_category_id = this.categoryList[0]['id'];
      }
    })
  }

  closeTaskModal() {
    this.taskModalVisible = false;
  }


  addTask(e) {
    e.stopPropagation();
    this.taskModalVisible = true;
    this.getTaskList();
  }

  dealTask(e, data) {
    this.taskList.map((item, i) => {
      if (item.id == data.id) {
        if (this.task_ids.length == 0) {
          if (e) {
            item['checked'] = true;
            this.task_ids.push(data);
          }
        } else {
          if (e) {
            let num = 0;
            this.task_ids.map((item1, i) => {
              if (item1.id != data.id && num === 0) {
                item['checked'] = true;
                this.task_ids.push(data);
                num++;
              }
              return;
            });
          } else {
            this.task_ids.map((item2, i) => {
              if (item2.id == data.id) {
                item['checked'] = false;
                this.task_ids.splice(i, 1);
                return;
              }
              return;
            });
          }
        }
      }
    });
    this.checkedTaskInfo = this.task_ids;
    if (this.checkedTaskInfo.length > 0) {
      this.taskRequired = false;
    } else {
      this.taskRequired = true;
    }
  }


  uploadImg1(data) {
    this.fileList.every((val, idx, array) => {
      if (val && val != "pic") {
        this.adOssUploadService.getSignature2(`/api/v1/common/upload`, '/v1/admin/tuike_activity/edit_activity', val, null)
          .subscribe(res => {
              if (res.code === 200) {
                data['pic'] = res.data[0];
                this.bannerService.addActivity(data).subscribe(res => {
                  if (res.code == 200) {
                    if (this.editId) {
                      this._message.create('success', '修改成功');
                    } else {
                      this._message.create('success', '添加成功');
                    }
                    this.submitStatus = false;
                    this.router.navigate(['tuike/activity/list']);
                  } else {
                    this.submitStatus = false;
                    if (this.editId) {
                      this._message.create('success', '修改失败');
                    } else {
                      this._message.create('error', '添加失败');
                    }
                  }
                })
              }
            }
          );
      } else {
        this.bannerService.addActivity(data).subscribe(res => {
          if (res.code == 200) {
            if (this.editId) {
              this._message.create('success', '修改成功');
            } else {
              this._message.create('success', '添加成功');
            }
            this.submitStatus = false;
            this.router.navigate(['tuike/activity/list']);
          } else {
            this.submitStatus = false;
            if (this.editId) {
              this._message.create('success', '修改失败');
            } else {
              this._message.create('error', '添加失败');
            }
          }
        });
      }
      return true;
    });
  }


  goBack() {
    this.page ?
    this.router.navigate(['tuike/activity/list'], {
      queryParams: {
        page: this.page
      }
    })
      :this.router.navigate(['tuike/activity/list']);
  }

  addActivityFormSubmit(e) {
    e.stopPropagation();
    let flag = true;
    if (this.checkedTaskInfo.length == 0) {
      this.taskRequired = true;
    } else {
      this.taskRequired = false;
      flag = true;
    }
    if (this.addActivity.activity_name === '') {
      this.nameRequired = true;
    } else {
      this.nameRequired = false;
      flag = true;
    }
    if (this.addActivity.sort === '') {
      this.sortRequired = true;
    } else {
      this.sortRequired = false;
      flag = true;
    }
    if (this.addActivity.comment === '') {
      this.commentRequired = true;
    } else {
      this.commentRequired = false;
      flag = true;
    }

    this.fileChange();

    if (this.checkedTaskInfo.length == 0 || this.addActivity.activity_name === '' || this.addActivity.sort === '' || this.picError || this.addActivity.comment === '' || this.nameError || this.commentError || this.sortError) {
      flag = false;
    }
    let data = Object.assign(this.addActivity);
    data['task_ids'] = [];
    this.checkedTaskInfo.map((e, i) => {
      data['task_ids'].push(e.id);
    });

    if (flag) {
      this.submitStatus = true;
      this.uploadImg1(data);
    }
  }

  sortError = false;


  checkSort(e) {
    console.log(e);
    if (e < 0) {
      this.sortError = true;
    } else {
      this.sortError = false;
    }
    if (!/^[0-9]+$/.test(e + '') && e !== '') {
      this.sortError = true;
    } else {
      this.sortError = false;
    }
    if (e === '') {
      this.sortRequired = true;
    } else {
      this.sortRequired = false;
    }
  }

  editActivityFormSubmit(e) {
    e.stopPropagation();
    let flag = true;
    if (this.checkedTaskInfo.length == 0) {
      this.taskRequired = true;
    } else {
      this.taskRequired = false;
      flag = true;
    }
    if (this.addActivity.activity_name === '') {
      this.nameRequired = true;
    } else {
      this.nameRequired = false;
      flag = true;
    }
    if (this.addActivity.sort === '') {
      this.sortRequired = true;
    } else {
      this.sortRequired = false;
      flag = true;
    }
    if (this.addActivity.comment === '') {
      this.commentRequired = true;
    } else {
      this.commentRequired = false;
      flag = true;
    }
    this.fileChange();
    if (this.checkedTaskInfo.length == 0 || this.addActivity.activity_name === '' || this.addActivity.sort === '' || this.picError || this.addActivity.comment === '' || this.nameError || this.commentError || this.sortError) {
      flag = false;
    }
    let data = Object.assign(this.addActivity);
    data['id'] = this.editId;
    data['task_ids'] = [];
    this.checkedTaskInfo.map((e, i) => {
      data['task_ids'].push(e.id);
    });
    if (flag) {
      this.submitStatus = true;
        this.uploadImg1(data);
    }
  }
}


class AddActivity {
  activity_name: string;
  type;
  pic;
  sort;
  comment: string;
  first_category_id;

  constructor() {
    this.activity_name = '';
    this.type = '2';
    this.comment = '';
    this.sort = '';
    this.first_category_id = '';
    this.pic = '';
  }
}

class EditActivity {
  activity_name: string;
  type;
  pic;
  sort;
  first_category_id;
  comment: string;

  constructor() {
    this.activity_name = '';
    this.type = '';
    this.comment = '';
    this.sort = '';
    this.first_category_id = '';
    this.pic = '';
  }
}
